<?php
namespace app\admin\controller;
use app\common\validate\AdminUser;
use think\Controller;
use app\common\lib\IAuth;

class Login extends Base
{
    //覆盖防止死循环
    public function _initialize(){}

    public function login()
    {
        $isLogin = $this->isLogin();
        if ($isLogin) {
           return $this->redirect('index/index');
        }else{
           //如果后台用户已经登录 那么需要跳转后台首页
           return $this->fetch();
        }
    }

    public function check()
    {
        if (request()->isPost()) {

            # code...
            $data = input('post.');
            //验证码
            if(!captcha_check($data['code'])) $this->error("验证码错误");

            //判定 username password
            //validate机制

            //username username+password

            try {
                $user = model('AdminUser')->get(['username'=>$data['username']]);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

           if (!$user || $user->status != config('code.status_normal')) {
               $this->error('用户不存在');
           }

           //对密码进行校验
           if(IAuth::setPassword($data['password']) != $user['password']){
                $this->error('密码不正确');
           }

           //1更新数据库 登录时间 登录ip
           $udata = [
                'last_login_time'=>time(),
                'last_login_ip'=>request()->ip(),
           ];
           try {
               model('AdminUser')->save($udata,['id'=>$user->id]);
           } catch (Exception $e) {
               $this->error($e->getMessage());
           }

           //2 session
           session(config('admin.session_user'),$user,config('admin.session_user_scope'));
           $this->success('登陆成功','index/index');
        }else{
            $this->error("请求不合法");
        }
    }

    /**
     * 退出登录
     * 1.清空isession
     * 2.跳转登录页面
     */
    public function logout(){
        session(null,config('admin.session_user_scope'));
        // 跳转
        $this->redirect('login/login');
    }
}
